/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controller.web;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import business.DaftarIndex;
import business.DaftarUser;
import business.Admin;
import business.ObatListing;
import business.Obat;
import business.User;
import business.Admin;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author atikahSH
 */
public class Login extends Servlet {

public Login(){
        super();
        setTemplate("/WEB-INF/index.jsp");
    }


    @Override
    protected void process() {
        HttpSession session = getRequest().getSession();
        DaftarUser du = new DaftarUser();
        String username = getRequest().getParameter("username");
        String password = getRequest().getParameter("password");
        //password = enkripsi.getEnkripsi(password);
        ObatListing dib = new ObatListing();

        List<Obat> i = dib.obatTerbaru();
            getRequest().setAttribute("obatListing", i.iterator());

        if (validate_field()) {
            User user = du.getUser(username);
            String d = user.getNama_depan();
            Admin ad = du.getAdmin(username);
            if (username.equals(user.getUsername()) && password.equals(user.getPassword())) {
                session.setAttribute("username", username);
                try {
                    getResponse().sendRedirect("userHome");
                } catch (IOException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                }
              } else if
                    (username.equals(ad.getUsername()) && password.equals(ad.getPassword())){
                    session.setAttribute("username", username);
                try {
                    getResponse().sendRedirect("adminHome");
                } catch (IOException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                }
                }

            } else {
                try {
                    getResponse().sendRedirect("Login");
                } catch (IOException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }


    boolean validate_field() {

        String username = getRequest().getParameter("username");
        String password = getRequest().getParameter("password");
        if(username == null||password == null){
            return false;
        }

        return true;
    }




}
